package com.knight.demo.control;

import com.knight.demo.service.StudentService;
import com.knight.spring.framework.annotation.KnightAutowired;
import com.knight.spring.framework.annotation.KnightController;
import com.knight.spring.framework.annotation.KnightRequestMapping;
import com.knight.spring.framework.annotation.KnightRequestParam;
import com.knight.spring.framework.web.servlet.KnightModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

@KnightController(value = "testController")
@KnightRequestMapping("test")
public class TestController {

    @KnightAutowired(value = "studentService")
    private StudentService studentService;

    @KnightRequestMapping("/query.json")
    public KnightModelAndView query(HttpServletRequest request, HttpServletResponse response,
                                    @KnightRequestParam("id") String id){
        String result = studentService.getStudentName(id);
        return out(response,result);
    }


    @KnightRequestMapping("/add*.json")
    public KnightModelAndView add(HttpServletRequest request,HttpServletResponse response,
                              @KnightRequestParam("name") String name,@KnightRequestParam("addr") String addr){
        String result = null;
        try {
            result = studentService.add(name,addr);
            return out(response,result);
        } catch (Exception e) {
//			e.printStackTrace();
            Map<String,Object> model = new HashMap<>();
            model.put("detail",e.getMessage());
//			System.out.println(Arrays.toString(e.getStackTrace()).replaceAll("\\[|\\]",""));
            model.put("stackTrace", Arrays.toString(e.getStackTrace()).replaceAll("\\[|\\]",""));
            return new KnightModelAndView("500",model);
        }

    }

    private KnightModelAndView out(HttpServletResponse resp,String str){
        try {
            resp.getWriter().write(str);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
